package com.mingserve.common.core.utils.poi;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.policy.HackLoopTableRenderPolicy;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.xddf.usermodel.chart.XDDFValueAxis;
import org.apache.poi.xwpf.usermodel.XWPFChart;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTTitle;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTTx;
import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph;

import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Word工具类
 *
 * @author lvwshuai
 * @date 2025-05-23
 */
@Slf4j
public final class WordUtils {

    private WordUtils() {
        // 私有构造方法，防止实例化
    }

    /**
     * 导出Word到输出流
     *
     * @param outputStream 输出流
     * @param templatePath 模板路径
     * @param map          标签内容
     * @param labelList    列表标签
     */
    public static void exportWord(OutputStream outputStream, String templatePath, Map<String, Object> map, List<String> labelList) {
        XWPFTemplate template = null;
        XWPFDocument doc = null;
        try {
            Pair<XWPFTemplate, XWPFDocument> pair = renderTemplate(templatePath, map, labelList);
            template = pair.getFirst();
            doc = pair.getSecond();

            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            doc.write(buffer);
            buffer.writeTo(outputStream);
        } catch (Exception ex) {
            log.error("导出Word异常", ex);
            throw new RuntimeException("导出Word失败", ex);
        } finally {
            IOUtils.closeQuietly(template);
            IOUtils.closeQuietly(doc);
        }
    }

    /**
     * 导出Word到字节数组
     *
     * @param templatePath 模板路径
     * @param map          标签内容
     * @param labelList    列表标签
     * @param titleMap     图表纵坐标标签
     * @return 字节数组
     */
    public static byte[] exportWordByte(String templatePath, Map<String, Object> map, List<String> labelList, Map<String, String> titleMap) {
        XWPFTemplate template = null;
        XWPFDocument doc = null;
        try {
            Pair<XWPFTemplate, XWPFDocument> pair = renderTemplate(templatePath, map, labelList);
            template = pair.getFirst();
            doc = pair.getSecond();

            if (titleMap != null) {
                updateChartTitles(doc, titleMap);
            }

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            doc.write(outputStream);
            return outputStream.toByteArray();
        } catch (Exception ex) {
            log.error("导出WordByte失败", ex);
            throw new RuntimeException("导出WordByte失败", ex);
        } finally {
            IOUtils.closeQuietly(template);
            IOUtils.closeQuietly(doc);
        }
    }

    /**
     * 渲染Word模板
     *
     * @param templatePath 模板路径
     * @param map          标签内容
     * @param labelList    列表标签
     */
    private static Pair<XWPFTemplate, XWPFDocument> renderTemplate(String templatePath, Map<String, Object> map, List<String> labelList) throws IOException {
        Map<String, Object> dataMap = map == null ? new HashMap<>() : new HashMap<>(map);

        File templateFile = isHttpUrl(templatePath) ?
                createTempFileByURL(templatePath) :
                createTempFile(templatePath);

        if (!templateFile.exists()) {
            throw new IllegalArgumentException("模板文件不存在");
        }

        ConfigureBuilder configBuilder = Configure.newBuilder();
        if (labelList != null) {
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
            for (String item : labelList) {
                configBuilder.bind(item, policy);
            }
        }

        Configure config = configBuilder.build();
        XWPFTemplate template = XWPFTemplate.compile(templateFile, config).render(dataMap);
        XWPFDocument doc = template.getXWPFDocument();

        return Pair.of(template, doc);
    }

    /**
     * 更新图表标题
     *
     * @param doc 文档
     * @param titleMap 标题映射
     */
    private static void updateChartTitles(XWPFDocument doc, Map<String, String> titleMap) {
        List<XWPFChart> charts = doc.getCharts();
        if (charts.isEmpty()) {
            return;
        }

        for (XWPFChart chart : charts) {
            String title = getChartTitle(chart);
            if (titleMap.containsKey(title)) {
                if (chart.getCTChart().getPlotArea().getValAxArray().length > 0) {
                    XDDFValueAxis valueAxis = new XDDFValueAxis(chart.getCTChart().getPlotArea().getValAxArray(0));
                    valueAxis.setTitle(titleMap.get(title));
                }
            }
        }
    }

    /**
     * 获取图表标题
     */
    public static String getChartTitle(XWPFChart chart) {
        CTChart ctChart = chart.getCTChart();
        if (ctChart.isSetTitle()) {
            CTTitle ctTitle = ctChart.getTitle();
            if (ctTitle.isSetTx()) {
                CTTx ctTx = ctTitle.getTx();
                if (ctTx.isSetStrRef()) {
                    return ctTx.getStrRef().getF();
                } else if (ctTx.isSetRich()) {
                    CTTextBody ctTextBody = ctTx.getRich();
                    StringBuilder titleBuilder = new StringBuilder();
                    for (CTTextParagraph ctTextParagraph : ctTextBody.getPList()) {
                        for (CTRegularTextRun ctRegularTextRun : ctTextParagraph.getRList()) {
                            titleBuilder.append(ctRegularTextRun.getT());
                        }
                    }
                    return titleBuilder.toString();
                }
            }
        }
        return "无标题";
    }

    /**
     * 创建临时文件
     */
    private static File createTempFile(String filePath) throws IOException {
        // this.getClass().getResourceAsStream() 需要 / 开头 从classpath根目录查找
        // 移除路径开头的"/" ClassLoader 所有路径都视为绝对路径（不能以/开头）
        String normalizedPath = filePath.startsWith("/") ? filePath.substring(1) : filePath;
        try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(normalizedPath)) {
            if (inputStream == null) {
                throw new FileNotFoundException("Template file template not found: " + filePath);
            }
            File tempFile = File.createTempFile("temp", "." + FilenameUtils.getExtension(filePath));
            tempFile.deleteOnExit();
            Files.copy(inputStream, tempFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
            return tempFile;
        }
    }

    /**
     * 从URL创建临时文件
     *
     * @param filePath 文件路径
     */
    private static File createTempFileByURL(String filePath) throws IOException {
        URL url = new URL(filePath);
        String fileName = new File(url.getFile()).getName();
        File tempFile = new File(System.getProperty("java.io.tmpdir"), fileName);

        try (InputStream in = url.openStream();
             OutputStream out = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }

        if (!isExpectedFileType(tempFile)) {
            tempFile.delete();
            throw new IOException("Invalid file type");
        }
        return tempFile;
    }

    private static boolean isHttpUrl(String path) {
        return path.matches("^https?://.*$");
    }

    private static boolean isExpectedFileType(File file) {
        return file.getName().endsWith(".docx");
    }

    // 简单的Pair实现
    @Getter
    private static class Pair<F, S> {
        private final F first;
        private final S second;

        private Pair(F first, S second) {
            this.first = first;
            this.second = second;
        }

        public static <F, S> Pair<F, S> of(F first, S second) {
            return new Pair<>(first, second);
        }
    }
}
